import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { API_CONFIG, HTTP_STATUS } from "@/config/api";
import { showToast } from "vant";

// 响应数据接口
export interface ApiResponse<T = any> {
  success: boolean;
  data: T;
  message: string;
  timestamp: string;
  error?: string;
  code?: number;
}

// 请求配置接口
export interface RequestConfig extends AxiosRequestConfig {
  showLoading?: boolean;
  showError?: boolean;
}

class HttpRequest {
  private instance: AxiosInstance;

  constructor() {
    // 创建axios实例
    this.instance = axios.create({
      baseURL: API_CONFIG.BASE_URL,
      timeout: API_CONFIG.TIMEOUT,
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });

    // 设置请求拦截器
    this.setupRequestInterceptor();

    // 设置响应拦截器
    this.setupResponseInterceptor();
  }

  // 请求拦截器
  private setupRequestInterceptor() {
    this.instance.interceptors.request.use(
      (config) => {
        // 添加认证token
        const token = this.getAuthToken();
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }

        // 开发环境打印请求信息
        if (API_CONFIG.DEBUG) {
          console.log("🚀 Request:", {
            method: config.method?.toUpperCase(),
            url: config.url,
            data: config.data,
            params: config.params,
          });
        }

        return config;
      },
      (error) => {
        console.error("❌ Request Error:", error);
        return Promise.reject(error);
      }
    );
  }

  // 响应拦截器
  private setupResponseInterceptor() {
    this.instance.interceptors.response.use(
      (response: AxiosResponse<ApiResponse>) => {
        // 开发环境打印响应信息
        if (API_CONFIG.DEBUG) {
          console.log("✅ Response:", {
            status: response.status,
            url: response.config.url,
            data: response.data,
          });
        }

        const { data } = response;

        // 检查业务状态码
        if (data.success === false) {
          const errorMessage = data.error || data.message || "请求失败";
          showToast(errorMessage);
          return Promise.reject(new Error(errorMessage));
        }

        return response;
      },
      (error) => {
        console.error("❌ Response Error:", error);

        // 处理HTTP错误状态码
        if (error.response) {
          const { status, data } = error.response;

          switch (status) {
            case HTTP_STATUS.UNAUTHORIZED:
              this.handleUnauthorized();
              break;
            case HTTP_STATUS.FORBIDDEN:
              showToast("权限不足");
              break;
            case HTTP_STATUS.NOT_FOUND:
              showToast("请求的资源不存在");
              break;
            case HTTP_STATUS.UNPROCESSABLE_ENTITY:
              // 处理表单验证错误
              this.handleValidationError(data);
              break;
            case HTTP_STATUS.INTERNAL_SERVER_ERROR:
              showToast("服务器内部错误");
              break;
            default:
              showToast(data?.message || "网络请求失败");
          }
        } else if (error.request) {
          showToast("网络连接失败，请检查网络设置");
        } else {
          showToast("请求配置错误");
        }

        return Promise.reject(error);
      }
    );
  }

  // 获取认证token
  private getAuthToken(): string | null {
    // 从localStorage获取token
    return localStorage.getItem("token");
  }

  // 处理未授权错误
  private handleUnauthorized() {
    // 清除token
    localStorage.removeItem("token");
    localStorage.removeItem("user");

    // 跳转到登录页
    showToast("登录已过期，请重新登录");

    // 这里可以使用router进行跳转
    // router.push('/login')
  }

  // 处理表单验证错误
  private handleValidationError(data: any) {
    if (data.errors) {
      // Laravel验证错误格式
      const firstError = Object.values(data.errors)[0] as string[];
      showToast(firstError[0]);
    } else {
      showToast(data.message || "数据验证失败");
    }
  }

  // GET请求
  public get<T = any>(
    url: string,
    config?: RequestConfig
  ): Promise<ApiResponse<T>> {
    return this.instance.get(url, config).then((res) => res.data);
  }

  // POST请求
  public post<T = any>(
    url: string,
    data?: any,
    config?: RequestConfig
  ): Promise<ApiResponse<T>> {
    return this.instance.post(url, data, config).then((res) => res.data);
  }

  // PUT请求
  public put<T = any>(
    url: string,
    data?: any,
    config?: RequestConfig
  ): Promise<ApiResponse<T>> {
    return this.instance.put(url, data, config).then((res) => res.data);
  }

  // DELETE请求
  public delete<T = any>(
    url: string,
    config?: RequestConfig
  ): Promise<ApiResponse<T>> {
    return this.instance.delete(url, config).then((res) => res.data);
  }

  // PATCH请求
  public patch<T = any>(
    url: string,
    data?: any,
    config?: RequestConfig
  ): Promise<ApiResponse<T>> {
    return this.instance.patch(url, data, config).then((res) => res.data);
  }

  // 上传文件
  public upload<T = any>(
    url: string,
    formData: FormData,
    config?: RequestConfig
  ): Promise<ApiResponse<T>> {
    return this.instance
      .post(url, formData, {
        ...config,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
      .then((res) => res.data);
  }
}

// 创建请求实例
const request = new HttpRequest();

export default request;
